<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <meta name="description" content="HyperSynapse Network 管理员控制台" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>管理员控制台 - HyperSynapse Phira</title>
  <!-- 复用account.html的样式 -->
  <style>
    html, body {
      margin: 0;
      padding: 0;
      font-family: 'Segoe UI', sans-serif;
      background: #000;
      color: #eee;
      overflow-x: hidden;
      scroll-behavior: smooth;
    }
    .parallax-bg {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), 
                        url('https://webstatic.cn-nb1.rains3.com/5712%C3%973360.jpeg');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      z-index: 0;
    }
    header {
      position: fixed;
      top: 0;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0.5rem 1.5rem;
      backdrop-filter: blur(12px);
      background: rgba(0, 0, 0, 0.4);
      z-index: 1000;
      box-sizing: border-box;
    }
    .logo-nav-container {
      display: flex;
      align-items: center;
      flex: 1;
    }
    #logo-img {
      height: 32px;
      margin-right: 1.2rem;
    }
    .nav-links {
      display: flex;
    }
    .nav-links a {
      color: #eee;
      margin-right: 1.2rem;
      text-decoration: none;
      transition: 0.3s;
      font-size: 0.95rem;
    }
    .nav-links a:hover {
      color: #fff;
      text-shadow: 0 0 4px #fff;
    }
    .user-section {
      display: flex;
      justify-content: flex-end;
      flex: 1;
    }
    .glass-button {
      display: flex;
      align-items: center;
      padding: 0.4rem 1rem;
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);
      border-radius: 999px;
      border: 1px solid rgba(255, 255, 255, 0.2);
      cursor: pointer;
      transition: all 0.3s ease;
      min-width: 100px;
    }
    .glass-button:hover {
      background: rgba(255, 255, 255, 0.15);
      transform: scale(1.05);
    }
    .login-btn {
      color: #eee;
      text-decoration: none;
      font-size: 0.95rem;
      white-space: nowrap;
      width: 100%;
      text-align: center;
    }
    .user-info {
      display: flex;
      align-items: center;
      position: relative;
      cursor: pointer;
      width: 100%;
    }
    .username {
      margin-right: 0.8rem;
      font-size: 0.95rem;
      color: #eee;
      max-width: 120px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .user-avatar {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      object-fit: cover;
      border: 1px solid rgba(255, 255, 255, 0.3);
    }
    .dropdown-content {
      position: absolute;
      top: 100%;
      right: 0;
      background: rgba(0, 0, 0, 0.7);
      backdrop-filter: blur(12px);
      border-radius: 8px;
      padding: 0.8rem;
      min-width: 160px;
      box-shadow: 0 4px 16px rgba(0,0,0,0.5);
      z-index: 1001;
      opacity: 0;
      visibility: hidden;
      transform: translateY(10px);
      transition: all 0.3s ease;
      border: 1px solid rgba(255, 255, 255, 0.1);
    }
    .dropdown-content.show {
      opacity: 1;
      visibility: visible;
      transform: translateY(0);
    }
    .dropdown-content span {
      display: block;
      padding: 0.3rem 0.5rem;
      font-weight: bold;
      color: #ffd700;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      margin-bottom: 0.5rem;
    }
    .dropdown-content a {
      display: block;
      padding: 0.5rem;
      color: #eee;
      text-decoration: none;
      border-radius: 4px;
      transition: all 0.3s ease;
    }
    .dropdown-content a:hover {
      background: rgba(255, 255, 255, 0.1);
      color: #fff;
    }
    main {
      position: relative;
      z-index: 2;
      padding-top: 100px;
      display: flex;
      flex-direction: column;
      align-items: center;
      min-height: 100vh;
      padding-bottom: 50px;
    }
    
    /* 新增3D卡片效果 */
    .account-container {
      transform-style: preserve-3d;
      transform: translateZ(20px);
      transition: transform 0.3s ease;
      animation: gentleSway 8s infinite ease-in-out;
      width: 95%;
      max-width: 800px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 16px;
      backdrop-filter: blur(12px);
      padding: 2rem;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
      border: 1px solid rgba(255, 255, 255, 0.2);
      margin: 1rem;
    }

    @keyframes gentleSway {
      0%, 100% { transform: translateZ(20px) rotateX(0.5deg) rotateY(0.5deg); }
      25% { transform: translateZ(20px) rotateX(-0.5deg) rotateY(-1deg); }
      50% { transform: translateZ(20px) rotateX(0.5deg) rotateY(1deg); }
      75% { transform: translateZ(20px) rotateX(-0.5deg) rotateY(0.5deg); }
    }

    .account-container.tilting {
      animation: none;
      transition: transform 0.1s linear;
    }
    
    .account-header {
      display: flex;
      align-items: center;
      margin-bottom: 2rem;
      padding-bottom: 1.5rem;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    .account-avatar {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      object-fit: cover;
      border: 1px solid rgba(255, 255, 255, 0.2);
      margin-right: 1.5rem;
      background: rgba(0, 0, 0, 0.3);
    }
    .account-info {
      flex: 1;
    }
    .account-name {
      font-size: 1.8rem;
      margin-bottom: 0.5rem;
      color: #fff;
    }
    .account-subtitle {
      color: #aaa;
      margin-bottom: 0.3rem;
      font-size: 1rem;
    }
    .account-stats {
      display: flex;
      margin-top: 1rem;
      gap: 1.5rem;
    }
    .stat-item {
      text-align: center;
    }
    .stat-value {
      font-size: 1.5rem;
      color: #ffd700;
      font-weight: bold;
    }
    .stat-label {
      font-size: 0.9rem;
      color: #aaa;
    }
    .form-section {
      margin-bottom: 2rem;
    }
    .section-title {
      font-size: 1.3rem;
      margin-bottom: 1.2rem;
      color: #ffd700;
      position: relative;
      padding-left: 1rem;
    }
    .section-title::before {
      content: "";
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      height: 70%;
      width: 4px;
      background: #ffd700;
      border-radius: 4px;
    }
    .form-group {
      margin-bottom: 1.5rem;
    }
    .form-label {
      display: block;
      margin-bottom: 0.5rem;
      color: #ddd;
    }
    .form-input {
      width: 100%;
      padding: 0.8rem 1rem;
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 8px;
      color: #fff;
      font-size: 1rem;
      outline: none;
      transition: all 0.3s ease;
    }
    .form-input:focus {
      border-color: rgba(255, 255, 255, 0.4);
      box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
    }
    .form-row {
      display: flex;
      gap: 1.5rem;
      margin-bottom: 1.5rem;
    }
    .form-col {
      flex: 1;
    }
    .badge {
      display: inline-block;
      padding: 0.3rem 0.8rem;
      border-radius: 999px;
      font-size: 0.85rem;
      margin-right: 0.5rem;
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(6px);
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    .badge-admin {
      background: rgba(255, 153, 0, 0.2);
      color: #ff9900;
    }
    .badge-dev {
      background: rgba(0, 204, 255, 0.2);
      color: #00ccff;
    }
    .btn {
      padding: 0.8rem 1.5rem;
      border-radius: 8px;
      border: none;
      font-size: 1rem;
      cursor: pointer;
      transition: all 0.3s ease;
      background: rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(10px);
      color: white;
      font-weight: 500;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    .btn:hover {
      background: rgba(255, 255, 255, 0.15);
      transform: translateY(-2px);
    }
    .btn-outline {
      background: transparent;
      border: 1px solid rgba(255, 255, 255, 0.2);
      color: #ddd;
    }
    .btn-outline:hover {
      background: rgba(255, 255, 255, 0.1);
    }
    .btn-container {
      display: flex;
      gap: 1rem;
      margin-top: 1rem;
    }
    .info-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 1.5rem;
      margin-top: 1rem;
    }
    .info-card {
      background: rgba(255, 255, 255, 0.05);
      border-radius: 12px;
      padding: 1.2rem;
      border: 1px solid rgba(255, 255, 255, 0.1);
      backdrop-filter: blur(6px);
    }
    .info-title {
      color: #aaa;
      font-size: 0.9rem;
      margin-bottom: 0.5rem;
    }
    .info-value {
      font-size: 1.1rem;
      color: #fff;
      word-break: break-all;
    }
    .status-indicator {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 0.5rem;
    }
    .status-active {
      background: #0f0;
      box-shadow: 0 0 8px #0f0;
    }
    .status-inactive {
      background: #f33;
    }
    .message {
      padding: 0.8rem;
      border-radius: 8px;
      margin: 1rem 0;
      text-align: center;
      display: none;
      backdrop-filter: blur(6px);
      border: 1px solid rgba(255, 255, 255, 0.1);
    }
    .message-success {
      background: rgba(0, 200, 0, 0.2);
      color: #0f0;
    }
    .message-error {
      background: rgba(200, 0, 0, 0.2);
      color: #f33;
    }
    .form-actions {
      display: flex;
      justify-content: flex-end;
      gap: 1rem;
      margin-top: 1rem;
    }
    @media (max-width: 768px) {
      header {
        padding: 0.5rem 1rem;
        flex-wrap: wrap;
      }
      .logo-nav-container {
        flex: 0 0 100%;
        margin-bottom: 0.5rem;
      }
      .user-section {
        flex: 0 0 100%;
        justify-content: flex-end;
      }
      .nav-links a {
        margin-right: 1rem;
      }
      .username {
        max-width: 80px;
      }
      .account-header {
        flex-direction: column;
        text-align: center;
      }
      .account-avatar {
        margin-right: 0;
        margin-bottom: 1rem;
      }
      .form-row {
        flex-direction: column;
        gap: 1rem;
      }
      .account-stats {
        justify-content: center;
      }
    }
    /* 添加管理员页面特有样式 */
    .admin-container {
      transform-style: preserve-3d;
      transform: translateZ(20px);
      transition: transform 0.3s ease;
      animation: gentleSway 8s infinite ease-in-out;
      width: 95%;
      max-width: 1200px;
      background: rgba(255, 255, 255, 0.05);
      border-radius: 16px;
      backdrop-filter: blur(12px);
      padding: 2rem;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
      border: 1px solid rgba(255, 255, 255, 0.2);
      margin: 1rem;
    }
    
    .admin-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 2rem;
      padding-bottom: 1.5rem;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .admin-title {
      font-size: 2rem;
      color: #ffd700;
    }
    
    .user-count {
      background: rgba(255, 215, 0, 0.2);
      color: #ffd700;
      padding: 0.5rem 1rem;
      border-radius: 999px;
      font-weight: bold;
    }
    
    .filters {
      display: flex;
      gap: 1rem;
      margin-bottom: 1.5rem;
      flex-wrap: wrap;
    }
    
    .filter-input {
      flex: 1;
      min-width: 250px;
      padding: 0.8rem 1rem;
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 8px;
      color: #fff;
      font-size: 1rem;
      outline: none;
    }
    
    .filter-input:focus {
      border-color: rgba(255, 255, 255, 0.4);
      box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
    }
    
    .users-table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 2rem;
    }
    
    .users-table th {
      text-align: left;
      padding: 1rem;
      background: rgba(255, 215, 0, 0.1);
      color: #ffd700;
      font-weight: 500;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .users-table td {
      padding: 1rem;
      border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }
    
    .user-row:hover {
      background: rgba(255, 255, 255, 0.03);
    }
    
    .user-avatar-small {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    
    .user-select {
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
    
    .badge {
      display: inline-block;
      padding: 0.3rem 0.8rem;
      border-radius: 999px;
      font-size: 0.85rem;
      margin-right: 0.5rem;
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    
    .badge-admin {
      background: rgba(255, 153, 0, 0.2);
      color: #ff9900;
    }
    
    .badge-dev {
      background: rgba(0, 204, 255, 0.2);
      color: #00ccff;
    }
    
    .actions-cell {
      display: flex;
      gap: 0.5rem;
    }
    
    .action-btn {
      padding: 0.4rem 0.8rem;
      border-radius: 6px;
      font-size: 0.9rem;
      cursor: pointer;
      transition: all 0.3s ease;
      background: rgba(255, 255, 255, 0.1);
      color: white;
      border: 1px solid rgba(255, 255, 255, 0.2);
    }
    
    .action-btn:hover {
      background: rgba(255, 255, 255, 0.15);
    }
    
    .btn-edit {
      background: rgba(0, 150, 255, 0.2);
      color: #0096ff;
    }
    
    .batch-actions {
      display: flex;
      gap: 1rem;
      margin-bottom: 2rem;
      flex-wrap: wrap;
    }
    
    .batch-form {
      display: flex;
      gap: 1rem;
      align-items: center;
      flex-wrap: wrap;
    }
    
    .batch-label {
      color: #ddd;
      font-size: 0.9rem;
    }
    
    .batch-select {
      padding: 0.6rem 1rem;
      background: rgba(255, 255, 255, 0.08);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 8px;
      color: #fff;
      min-width: 150px;
    }
    
    .message {
      padding: 0.8rem;
      border-radius: 8px;
      margin: 1rem 0;
      text-align: center;
      display: none;
      backdrop-filter: blur(6px);
      border: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .message-success {
      background: rgba(0, 200, 0, 0.2);
      color: #0f0;
    }
    
    .message-error {
      background: rgba(200, 0, 0, 0.2);
      color: #f33;
    }
    
    /* 模态框样式 */
    .modal {
      position: fixed;
      top: 0; left: 0;
      width: 100vw; height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      background: rgba(0,0,0,0.7);
      backdrop-filter: blur(10px);
      z-index: 9999;
      display: none;
    }
    
    .modal-content {
      background: rgba(30, 30, 40, 0.9);
      padding: 2rem;
      border-radius: 16px;
      color: #fff;
      backdrop-filter: blur(20px);
      max-width: 500px;
      width: 90%;
      border: 1px solid rgba(255, 255, 255, 0.2);
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
    }
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1.5rem;
    }
    
    .modal-title {
      font-size: 1.5rem;
      color: #ffd700;
      margin: 0;
    }
    
    .close-modal {
      background: none;
      border: none;
      color: #aaa;
      font-size: 1.5rem;
      cursor: pointer;
      transition: color 0.3s;
    }
    
    .close-modal:hover {
      color: #fff;
    }
    
    .modal-body {
      margin-bottom: 1.5rem;
    }
    
    .modal-footer {
      display: flex;
      justify-content: flex-end;
      gap: 1rem;
    }
    
    .password-display {
      background: rgba(0, 0, 0, 0.3);
      padding: 0.8rem;
      border-radius: 8px;
      font-family: monospace;
      word-break: break-all;
      margin: 0.5rem 0;
    }
    
    .reveal-btn {
      background: rgba(255, 215, 0, 0.2);
      color: #ffd700;
      border: none;
      padding: 0.3rem 0.8rem;
      border-radius: 4px;
      cursor: pointer;
      font-size: 0.9rem;
    }
  </style>
</head>
<body>
  <div class="parallax-bg"></div>
  <header>
    <div class="logo-nav-container">
      <img id="logo-img" src="logo.png" alt="logo" />
      <div class="nav-links">
        <a href="index.html">主页</a>
        <a href="rooms.html">房间列表</a>
        <a href="account.html">账号管理</a>
        <a href="admin.html" style="color: #ffd700;">管理员控制台</a>
      </div>
    </div>
    
    <div class="user-section">
      <div id="avatar-container" class="glass-button">
        <div class="user-info" onclick="toggleDropdown()">
          <span class="username" id="username-display"></span>
          <img id="user-avatar" src="" alt="用户头像" class="user-avatar" />
        </div>
        <div class="dropdown-content" id="user-dropdown">
          <span id="dropdown-username"></span>
          <a id="phira-profile-link" target="_blank">我的Phira账户</a>
          <a href="account.html">账号管理</a>
          <a href="javascript:void(0)" onclick="logout()">退出登录</a>
        </div>
      </div>
    </div>
  </header>
  
  <main>
    <div class="admin-container">
      <div class="admin-header">
        <h1 class="admin-title">管理员控制台</h1>
        <div class="user-count">用户总数: <span id="total-users">0</span></div>
      </div>
      
      <div class="filters">
        <input type="text" class="filter-input" id="search-name" placeholder="搜索用户名..." />
        <input type="text" class="filter-input" id="search-phira" placeholder="搜索Phira ID..." />
        <select class="filter-input" id="filter-admin">
          <option value="all">所有管理员状态</option>
          <option value="yes">管理员</option>
          <option value="no">非管理员</option>
        </select>
        <select class="filter-input" id="filter-dev">
          <option value="all">所有开发者状态</option>
          <option value="yes">开发者</option>
          <option value="no">非开发者</option>
        </select>
      </div>
      
      <div class="batch-actions">
        <div class="batch-form">
          <span class="batch-label">批量操作:</span>
          <select class="batch-select" id="batch-action">
            <option value="set_admin">设为管理员</option>
            <option value="remove_admin">取消管理员</option>
            <option value="set_dev">设为开发者</option>
            <option value="remove_dev">取消开发者</option>
          </select>
          <button class="btn" onclick="applyBatchAction()">应用</button>
          <button class="btn btn-outline" onclick="selectAllUsers()">全选</button>
          <button class="btn btn-outline" onclick="deselectAllUsers()">取消全选</button>
        </div>
      </div>
      
      <div id="admin-message" class="message"></div>
      
      <div class="table-container">
        <table class="users-table">
          <thead>
            <tr>
              <th><input type="checkbox" id="select-all" class="user-select" /></th>
              <th>ID</th>
              <th>用户名</th>
              <th>头像</th>
              <th>Phira ID</th>
              <th>Phira 用户名</th>
              <th>RKS</th>
              <th>权限</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody id="users-table-body">
            <!-- 用户数据将通过JavaScript填充 -->
          </tbody>
        </table>
      </div>
    </div>
  </main>
  
  <!-- 编辑用户模态框 -->
  <div id="edit-modal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">编辑用户信息</h3>
        <button class="close-modal" onclick="closeEditModal()">&times;</button>
      </div>
      <div class="modal-body">
        <div id="edit-message" class="message"></div>
        
        <input type="hidden" id="edit-user-id" />
        
        <div class="form-group">
          <label class="form-label">用户名</label>
          <input type="text" class="form-input" id="edit-username" />
        </div>
        
        <div class="form-group">
          <label class="form-label">密码</label>
          <div class="password-display" id="password-display">************</div>
          <button class="reveal-btn" onclick="togglePasswordDisplay()">显示/隐藏密码</button>
          <input type="password" class="form-input" id="edit-password" placeholder="输入新密码" style="margin-top: 0.5rem;" />
        </div>
        
        <div class="form-group">
          <label class="form-label">Phira ID</label>
          <input type="text" class="form-input" id="edit-phira-id" />
        </div>
        
        <div class="form-row">
          <div class="form-col">
            <label class="form-label">管理员状态</label>
            <select class="form-input" id="edit-admin">
              <option value="no">否</option>
              <option value="yes">是</option>
            </select>
          </div>
          <div class="form-col">
            <label class="form-label">开发者权限</label>
            <select class="form-input" id="edit-dev">
              <option value="no">否</option>
              <option value="yes">是</option>
            </select>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-outline" onclick="closeEditModal()">取消</button>
        <button class="btn" onclick="saveUserChanges()">保存更改</button>
      </div>
    </div>
  </div>
  
  <!-- 管理员密码模态框 -->
  <div id="admin-password-modal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">管理员验证</h3>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label class="form-label">请输入管理员密码</label>
          <input type="password" class="form-input" id="admin-password-input" placeholder="管理员密码" />
        </div>
        <div id="admin-password-message" class="message"></div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-outline" onclick="closeAdminPasswordModal()">取消</button>
        <button class="btn" onclick="verifyAdminPassword()">验证</button>
      </div>
    </div>
  </div>
  
  <script>
    // 全局变量
    let allUsers = [];
    let adminPassword = '';
    let isSuperAdmin = false;
    
    // 页面加载时检查登录状态和管理员权限
    document.addEventListener('DOMContentLoaded', () => {
      const savedUser = localStorage.getItem('user');
      if (savedUser) {
        currentUser = JSON.parse(savedUser);
        
        // 检查是否为管理员
        if (currentUser.admin !== "yes") {
          alert('您不是管理员，无法访问此页面');
          window.location.href = 'index.html';
          return;
        }
        
        updateUserDisplay();
        showAdminPasswordModal();
      } else {
        // 未登录，重定向到登录页
        window.location.href = 'index.html';
      }
    });
    
    // 显示管理员密码验证模态框
    function showAdminPasswordModal() {
      document.getElementById('admin-password-modal').style.display = 'flex';
    }
    
    // 关闭管理员密码验证模态框
    function closeAdminPasswordModal() {
      window.location.href = 'account.html';
    }
    
    // 验证管理员密码
    function verifyAdminPassword() {
      const password = document.getElementById('admin-password-input').value;
      const messageElement = document.getElementById('admin-password-message');
      
      if (!password) {
        messageElement.textContent = '请输入管理员密码';
        messageElement.className = 'message message-error';
        messageElement.style.display = 'block';
        return;
      }
      
      // 尝试获取用户数据来验证密码
      fetch('/admin/users', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ password })
      })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'success') {
          adminPassword = password;
          isSuperAdmin = data.users.some(u => u.password); // 如果有密码字段返回，说明是超级管理员
          document.getElementById('admin-password-modal').style.display = 'none';
          loadAllUsers();
        } else {
          messageElement.textContent = data.message || '密码验证失败';
          messageElement.className = 'message message-error';
          messageElement.style.display = 'block';
        }
      })
      .catch(error => {
        messageElement.textContent = '网络错误，请重试';
        messageElement.className = 'message message-error';
        messageElement.style.display = 'block';
      });
    }
    
    // 加载所有用户数据
    function loadAllUsers() {
      fetch('/admin/users', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ password: adminPassword })
      })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'success') {
          allUsers = data.users;
          document.getElementById('total-users').textContent = allUsers.length;
          renderUsersTable(allUsers);
        } else {
          showAdminMessage(data.message || '加载用户数据失败', false);
        }
      })
      .catch(error => {
        showAdminMessage('网络错误，请重试', false);
      });
    }
    
    // 渲染用户表格
    function renderUsersTable(users) {
      const tableBody = document.getElementById('users-table-body');
      tableBody.innerHTML = '';
      
      const searchName = document.getElementById('search-name').value.toLowerCase();
      const searchPhira = document.getElementById('search-phira').value.toLowerCase();
      const filterAdmin = document.getElementById('filter-admin').value;
      const filterDev = document.getElementById('filter-dev').value;
      
      // 过滤用户
      const filteredUsers = users.filter(user => {
        const nameMatch = user.name.toLowerCase().includes(searchName);
        const phiraMatch = user.phira_id.toLowerCase().includes(searchPhira);
        const adminMatch = filterAdmin === 'all' || user.admin === filterAdmin;
        const devMatch = filterDev === 'all' || user.dev === filterDev;
        
        return nameMatch && phiraMatch && adminMatch && devMatch;
      });
      
      // 填充表格
      filteredUsers.forEach(user => {
        const row = document.createElement('tr');
        row.className = 'user-row';
        row.innerHTML = `
          <td><input type="checkbox" class="user-select" data-id="${user.id}" /></td>
          <td>${user.id}</td>
          <td>${user.name}</td>
          <td><img src="${user.image_url || 'https://phira.moe/assets/user-6212ee95.png'}" class="user-avatar-small" /></td>
          <td>${user.phira_id}</td>
          <td>${user.phira_name}</td>
          <td>${user.phira_rks ? parseFloat(user.phira_rks).toFixed(2) : '0.00'}</td>
          <td>
            ${user.admin === 'yes' ? '<span class="badge badge-admin">管理员</span>' : ''}
            ${user.dev === 'yes' ? '<span class="badge badge-dev">开发者</span>' : ''}
          </td>
          <td class="actions-cell">
            <button class="action-btn btn-edit" onclick="openEditModal(${user.id})">编辑</button>
          </td>
        `;
        tableBody.appendChild(row);
      });
    }
    
    // 打开编辑用户模态框
    function openEditModal(userId) {
      const user = allUsers.find(u => u.id === userId);
      if (!user) return;
      
      document.getElementById('edit-user-id').value = user.id;
      document.getElementById('edit-username').value = user.name;
      document.getElementById('edit-phira-id').value = user.phira_id;
      document.getElementById('edit-admin').value = user.admin;
      document.getElementById('edit-dev').value = user.dev;
      
      // 存储原始密码用于比较
      document.getElementById('password-display').dataset.original = user.password;
      
      document.getElementById('edit-message').style.display = 'none';
      document.getElementById('edit-modal').style.display = 'flex';
    }
    
    // 关闭编辑用户模态框
    function closeEditModal() {
      document.getElementById('edit-modal').style.display = 'none';
    }
    
    // 切换密码显示
    function togglePasswordDisplay() {
      const display = document.getElementById('password-display');
      if (display.textContent === '************') {
        display.textContent = display.dataset.original;
      } else {
        display.textContent = '************';
      }
    }
    
    // 保存用户更改
    function saveUserChanges() {
      const userId = parseInt(document.getElementById('edit-user-id').value);
      const username = document.getElementById('edit-username').value;
      const password = document.getElementById('edit-password').value;
      const phiraId = document.getElementById('edit-phira-id').value;
      const admin = document.getElementById('edit-admin').value;
      const dev = document.getElementById('edit-dev').value;
      
      const changes = {
        name: username,
        admin,
        dev
      };
      
      if (phiraId) changes.phira_id = phiraId;
      if (password) changes.password = password;
      
      fetch('/admin/update', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          password: adminPassword,
          user_id: userId,
          changes
        })
      })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'success') {
          showEditMessage('用户信息更新成功', true);
          // 重新加载用户数据
          setTimeout(() => {
            closeEditModal();
            loadAllUsers();
          }, 1500);
        } else {
          showEditMessage(data.message || '更新失败', false);
        }
      })
      .catch(error => {
        showEditMessage('网络错误，请重试', false);
      });
    }
    
    // 显示编辑消息
    function showEditMessage(message, isSuccess) {
      const messageElement = document.getElementById('edit-message');
      messageElement.textContent = message;
      messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
      messageElement.style.display = 'block';
    }
    
    // 全选用户
    function selectAllUsers() {
      document.querySelectorAll('.user-select').forEach(checkbox => {
        checkbox.checked = true;
      });
    }
    
    // 取消全选
    function deselectAllUsers() {
      document.querySelectorAll('.user-select').forEach(checkbox => {
        checkbox.checked = false;
      });
    }
    
    // 应用批量操作
    function applyBatchAction() {
      const action = document.getElementById('batch-action').value;
      const selectedUserIds = [];
      
      document.querySelectorAll('.user-select:checked').forEach(checkbox => {
        if (checkbox.id !== 'select-all') {
          selectedUserIds.push(parseInt(checkbox.dataset.id));
        }
      });
      
      if (selectedUserIds.length === 0) {
        showAdminMessage('请选择至少一个用户', false);
        return;
      }
      
      // 确定要应用的更改
      let changes = {};
      switch (action) {
        case 'set_admin':
          changes.admin = 'yes';
          break;
        case 'remove_admin':
          changes.admin = 'no';
          break;
        case 'set_dev':
          changes.dev = 'yes';
          break;
        case 'remove_dev':
          changes.dev = 'no';
          break;
      }
      
      fetch('/admin/batch-update', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          password: adminPassword,
          user_ids: selectedUserIds,
          changes
        })
      })
      .then(response => response.json())
      .then(data => {
        if (data.status === 'success') {
          // 统计成功和失败的数量
          const successCount = data.results.filter(r => r.status === 'success').length;
          const errorCount = data.results.filter(r => r.status === 'error').length;
          
          if (errorCount === 0) {
            showAdminMessage(`成功更新 ${successCount} 个用户`, true);
          } else {
            showAdminMessage(`成功更新 ${successCount} 个用户，失败 ${errorCount} 个`, false);
          }
          
          // 重新加载用户数据
          loadAllUsers();
        } else {
          showAdminMessage(data.message || '批量更新失败', false);
        }
      })
      .catch(error => {
        showAdminMessage('网络错误，请重试', false);
      });
    }
    
    // 显示管理员消息
    function showAdminMessage(message, isSuccess) {
      const messageElement = document.getElementById('admin-message');
      messageElement.textContent = message;
      messageElement.className = `message ${isSuccess ? 'message-success' : 'message-error'}`;
      messageElement.style.display = 'block';
      
      // 5秒后隐藏消息
      setTimeout(() => {
        messageElement.style.display = 'none';
      }, 5000);
    }
    
    // 绑定搜索和过滤事件
    document.getElementById('search-name').addEventListener('input', () => renderUsersTable(allUsers));
    document.getElementById('search-phira').addEventListener('input', () => renderUsersTable(allUsers));
    document.getElementById('filter-admin').addEventListener('change', () => renderUsersTable(allUsers));
    document.getElementById('filter-dev').addEventListener('change', () => renderUsersTable(allUsers));
    
    // 全选/取消全选
    document.getElementById('select-all').addEventListener('change', function() {
      document.querySelectorAll('.user-select').forEach(checkbox => {
        checkbox.checked = this.checked;
      });
    });
    
    // 复用account.html中的函数
    function updateUserDisplay() {
      if (currentUser) {
        document.getElementById('username-display').textContent = currentUser.name;
        document.getElementById('user-avatar').src = currentUser.image_url || 'https://phira.moe/assets/user-6212ee95.png';
        document.getElementById('dropdown-username').textContent = currentUser.name;
      }
    }
    
    function toggleDropdown() {
      const dropdown = document.getElementById('user-dropdown');
      if (dropdown) {
        dropdown.classList.toggle('show');
      }
    }
    
    function logout() {
      localStorage.removeItem('user');
      window.location.href = 'index.html';
    }
  </script>
</body>
</html>